package com.ctsi.supportflow.mybatis.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.nio.charset.Charset;
import java.sql.*;

public class BlobToStringTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Blob blob = rs.getBlob(columnName);
        if (blob == null){
            return "";
        }
        return new String(blob.getBytes(1, (int)blob.length()), Charset.defaultCharset());
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Blob blob = rs.getBlob(columnIndex);
        if (blob == null){
            return "";
        }
        return new String(blob.getBytes(1, (int)blob.length()),Charset.defaultCharset());
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Blob blob = cs.getBlob(columnIndex);
        if (blob == null){
            return "";
        }
        return new String(blob.getBytes(1, (int)blob.length()),Charset.defaultCharset());
    }
}
